package com.edushare.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import com.edushare.R;
import com.edushare.controller.GroupMediaController;
import com.edushare.controller.HttpUploader;
import com.edushare.entity.GroupMedia;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.provider.MediaStore.Images.Media;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;


public class GroupMedias extends Activity{

	private GroupMediaController gc = new GroupMediaController();
	ArrayList<GroupMedia> groupList = new ArrayList<GroupMedia>();

	public static final String LOG_TAG = "EduShare";
	public static final String PICTURE_FILE_ID = "picture";
	public static final String TMP_FILE_NAME = ".unifiq";
	private static final int CAMERA_REQUEST_CODE = 666;
	private static final int GALLERY_REQUEST_CODE = 777;
	private File mPictureFile;
	String imagename = "";
	int mediaID;

	private void saveImage(ImageView iv){
		Bitmap b = iv.getDrawingCache();
		Uri path = this.getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
		try{
			OutputStream stream = this.getContentResolver().openOutputStream(path);
			b.compress(CompressFormat.JPEG, 90, stream);
		}catch( FileNotFoundException e){
			Log.e("edushare image", "E: " + e.getMessage());
		}
	}

	/**
	 * Starts draw activity with given background.
	 */
	private void draw() {
		if (mPictureFile != null) {
			Intent intent = new Intent(this, DrawActivity.class);
			intent.putExtra(PICTURE_FILE_ID, mPictureFile);
			startActivity(intent);
		}
	}
	
	private class MyNetworkTask extends AsyncTask<URL, Void, Bitmap> {

		ImageView tIV;
		ProgressBar pb;

		public MyNetworkTask(ImageView iv, ProgressBar progBar) {
			tIV = iv;
			pb = progBar;
		}// constructor

		@Override
		protected Bitmap doInBackground(URL... urls) {

			Bitmap networkBitmap = null;

			URL networkUrl = urls[0]; // Load the first element
			try {
				networkBitmap = BitmapFactory.decodeStream(networkUrl
						.openConnection().getInputStream());
			} catch (IOException e) {
				e.printStackTrace();
			}

			return networkBitmap;
		}// return bitmap

		@Override
		protected void onPostExecute(Bitmap result) {
			tIV.setImageBitmap(result);
			tIV.setVisibility(View.VISIBLE);
			pb.setVisibility(View.GONE);
		}// hide progress bar

	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.groupmedia);

		new LoadMedias().execute();

	}

	@Override
	public void onResume() {
		super.onResume();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu,
			View v, ContextMenuInfo menuInfo) {

		menu.setHeaderTitle("Media Options");
		menu.add(0, v.getId(), 0, "Draw on a picture");
		menu.add(0, v.getId(), 0, "Change media");
		menu.add(0, v.getId(), 0, "View comments");

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Draw on a picture") {
			loadPicture();
		} else if (item.getTitle() == "Change media") {
			mediaID = item.getItemId();
			replacePicture();
		} else if (item.getTitle() == "View comments") {
			Intent mIntent = new Intent(this, DrawCommentActivity.class);
			Bundle extras = mIntent.getExtras();
			extras.putString("mediaID", String.valueOf(item.getItemId()) );
		}
		return true;
	}
	
	class LoadMedias extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... args) {
			// get intent values
			Intent i = getIntent();
			int gid = i.getExtras().getInt("groupid");
			groupList = gc.retrieveGroupsMedia(Integer.toString(gid));
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute(String file_url) {			
			LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
			if(!groupList.isEmpty()){
			for (int i = 0; i < groupList.size(); i++) {

			        final ImageView image = new ImageView(GroupMedias.this);
			        ProgressBar pb = new ProgressBar(GroupMedias.this);
			        
			        ll.addView(image);
			        ll.addView(pb);
			        
					// Load bitmap from internet
					URL onLineURL;
					try {
						onLineURL = new URL(groupList.get(i).getImagePath());
						new MyNetworkTask(image, pb)
								.execute(onLineURL);
					} catch (MalformedURLException e) {
						e.printStackTrace();
					}

			        image.getLayoutParams().height = 300;
			        image.getLayoutParams().width = 300;
			        image.setId(i+1);
			        
			        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
			        lp.setMargins(25,25,25,25);
			        image.setLayoutParams(lp);
					registerForContextMenu(image);

				    
				    /*
				int mid = groupList.get(i).getMediaID();
				String turl = groupList.get(i).getImagePath();

				GroupMedia _GroupModel = new GroupMedia();
				_GroupModel.setGroupID(mid);
				_GroupModel.setImagePath(turl);

				_groupList.add(_GroupModel);*/
			}
			}
			/*
			listview = (ListView) findViewById(R.id.groupList);
			ListAdapter myAdapter = new ListAdapter(GroupMedias.this);
			listview.setAdapter(myAdapter);
			myAdapter.notifyDataSetChanged();
			
			listview.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int temp,
						long arg3) {

					int _groupID = _groupList.get(temp).getGroupID();
					String _groupimagepath = _groupList.get(temp).getImagePath()
							.trim();

					Intent intent = new Intent(GroupMedias.this, GroupMedias.class);

					Bundle bundle = new Bundle();
					bundle.putInt("groupid", _groupID);
					bundle.putString("groupimagepath", _groupimagepath);

					intent.putExtras(bundle);
					startActivity(intent);

				}
			});
			*/
		}
	}
	
	/**
	 * Starts an activity for loading a picture.
	 */
	private void loadPicture() {
		Intent intent = new Intent(Intent.ACTION_PICK,
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, GALLERY_REQUEST_CODE);
	}

	/**
	 * Starts an activity for replacing picture
	 */
	private void replacePicture() {
		// To open up a gallery browser
		Intent intent = new Intent();
		intent.setType("image/*");
		intent.setAction(Intent.ACTION_GET_CONTENT);
		startActivityForResult(Intent.createChooser(intent, "Select Picture"),
				1);

	}

	/**
	 * Gets path of an image from the gallery.
	 * 
	 * @param uri
	 *            Image Uri
	 * @return Image absolute path
	 */
	private String getImagePath(final Uri uri) {
		String[] projection = { MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(uri, projection, null, null,
				null);
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}

	@Override
	protected void onActivityResult(final int requestCode,
			final int resultCode, final Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CAMERA_REQUEST_CODE:
				draw();
				break;
			case GALLERY_REQUEST_CODE:
				mPictureFile = new File(getImagePath(data.getData()));
				draw();
				break;
			case 1:
				Uri currImageURI = data.getData();
				System.out.println("Current image Path is "
						+ getRealPathFromURI(currImageURI));

				HttpUploader uploader = new HttpUploader();
				try {
					imagename = uploader.execute(
							getRealPathFromURI(currImageURI)).get();
					new UpdateIcon().execute();

				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (ExecutionException e) {
					e.printStackTrace();
				}

				break;
			default:
				break;
			}
		}
	}

	class UpdateIcon extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		protected String doInBackground(String... args) {
			// TODO 
			gc.updateGroupIcon(mediaID, imagename);
			return null;
		}

		protected void onPostExecute(String file_url) {

			// Load bitmap from internet
			URL onLineURL;
			try {
				onLineURL = new URL(
						"http://unifiq.5kportal.com/images/post_images/"
								+ imagename);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			}
		}
	}

	private String getRealPathFromURI(Uri contentUri) {

		String[] proj = { MediaColumns.DATA };
		android.database.Cursor cursor = getContentResolver().query(contentUri,
				proj, // Which
				// columns
				// to
				// return
				null, // WHERE clause; which rows to return (all rows)
				null, // WHERE clause selection arguments (none)
				null); // Order-by clause (ascending by name)
		int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}


}
